<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: 100%"
  >
    <a-spin :spinning="confirmLoading">
      <j-form-container :disabled="formDisabled">
        <!-- 主表单区域 -->
        <a-form-model
          ref="form"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :model="model"
          :rules="validatorRules"
          slot="detail"
        >
          <a-row class="form-row" :gutter="16">
            <a-col :lg="8">
              <a-form-model-item label="算法名称" prop="formulaName">
                <a-input v-model="model.formulaName" placeholder="请输入算法名称"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :lg="12">
              <a-form-model-item label="备注" prop="remark">
                <a-textarea v-model="model.remark" rows="1" placeholder="请输入备注" />
              </a-form-model-item>
            </a-col> 
          </a-row>

          <!-- <a-col :span="12" >
            <a-form-model-item label="序号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="seqNo">
              <a-input-number v-model="model.seqNo" placeholder="请输入序号" style="width: 100%" />
            </a-form-model-item>
          </a-col> -->
          <a-row class="form-row" :gutter="16">
            <a-col :lg="24">
              <a-form-model-item
                label="内容"
                v-if="isEdit" 
                prop="formulaContentHtml"
                :labelCol="{ lg: { span: 2 }, sm: { span: 3 } }"
                :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
              >
                <w-textarea
                  ref="wText"
                  tag="wise"
                  v-model="model.formulaContentHtml"
                  :tools="[{ type: 'tag', text: '插入函数' }]"
                  @add="addLink"
                  style="font-size: 22px"
                />
                <!-- {{model.formulaContentHtml}} --> 
                <!-- <a-textarea style="color:#ddd;" v-model="model.formulaContent" rows="2"  readonly="readonly" placeholder="请输入内容" /> -->
              </a-form-model-item>
              <!-- {{model.formulaContentHtml}} -->
            </a-col>
          </a-row>
          <!-- <a-input v-model="addFunText"></a-input>
   <a-button type="primary"  style="margin-right: 0.8rem"  @click="handleAddFunSubmit"  >保存</a-button> -->
          <a-form-model-item :wrapperCol="{ lg: { span: 12 }, sm: { span: 17 } }" style="padding-left:120px;">
            <a-button type="primary" style="margin-right: 0.8rem" @click="handleSave" :loading="loading">保存</a-button>
            <a-button @click="handleCancel">取消</a-button>
          </a-form-model-item>
        </a-form-model>
      </j-form-container>
      <template v-if="isEdit">
        <!-- 子表单区域 -->
        <a-tabs type="card" v-model="activeKey">
          <a-tab-pane tab="引用函数" :key="refKeys[0]" :forceRender="true">
            <user-formula-detail
              :ref="refKeys[0]"
              :formulaId="formulaId"
              @addTagFormulaContent="addTagFormulaContent"
              @refreshFormulaContent="refreshFormulaContent"
            />
          </a-tab-pane>
          <a-tab-pane tab="运行结果区间设置" :key="refKeys[1]" :forceRender="true">
            <user-formula-portion :ref="refKeys[1]" :formulaId="formulaId" />
          </a-tab-pane>
        </a-tabs>
      </template>
      <!-- <footer-tool-bar>
      <a-button style="margin-right: 0.8rem" @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleSave" :loading="loading">保存</a-button>
    </footer-tool-bar> -->
    </a-spin>
    <!-- <a-modal
      title="插入函数"
      :width="400"
      :visible="insertFunVisible"
      :confirmLoading="funConfirmLoading"
      @ok="handleAddFunSubmit"
      @cancel="handleAddFunCancel"
    >
      <j-search-select-tag placeholder="请选择" v-model="addFunText" :dictOptions="searchOptions">
      </j-search-select-tag>

      
    </a-modal> -->

    <a-modal
      title="插入函数"
      destroyOnClose
      :visible="insertFunVisible"
      :confirmLoading="funConfirmLoading"
      @ok="handleAddFunSubmit"
      @cancel="handleAddFunCancel"
    >
      <!---->
      <a-form
        style="margin-top: 8px"
        :autoFormCreate="
          (form) => {
            this.createForm = form
          }
        "
      >
        <a-form-item
          :labelCol="{ span: 5 }"
          :wrapperCol="{ span: 15 }"
          label="函数"
          fieldDecoratorId="description"
          :fieldDecoratorOptions="{ rules: [{ required: true, message: '请选择函数！' }] }"
        >
          <j-search-select-tag placeholder="请选择" v-model="addFunText" :dictOptions="searchOptions">
          </j-search-select-tag>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-drawer>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import JFormContainer from '@/components/jeecg/JFormContainer'
import UserFormulaDetail from './detail/UserFormulaDetail'
import UserFormulaPortion from './detail/UserFormulaPortion'
import FooterToolBar from '@/components/tools/FooterToolBar'
import { duplicateCheck } from '@/api/api'
export default {
  name: 'UserFormulaForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    UserFormulaDetail,
    UserFormulaPortion,
    FooterToolBar,
  },
  data() {
    return {
      title: '算法',
      formulaId: this.$route.params.formulaId,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        formulaName: '',
        remark: '',
        formulaContent: '',
        formulaContentHtml: '',
      },
      insertFunVisible: false,
      funConfirmLoading: false,
      addFunText: '',
      searchOptions: [],
      loading: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        formulaName: [{ required: true, message: '请输入算法名称!' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        // , { validator: this.validateUsername }
        ],
        remark:[ { min: 0, max: 200, message: '长度在200 个字符以内', trigger: 'blur' }],
        formulaContentHtml: [{ required: true, message: '请输入内容!' }],
      },
      isEdit: false, //是否编辑
      refKeys: ['userFormulaDetail', 'userFormulaPortion'],
      tableKeys: ['userFormulaDetail', 'userFormulaPortion'],
      activeKey: 'userFormulaDetail', 
      // 引用函数
      userFormulaDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '函数ID',
            key: 'funId',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '函数类型',
            key: 'funType',
            type: JVXETypes.select,
            options: [],
            dictCode: 'fun_type',
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '函数参数',
            key: 'funPara',
            type: JVXETypes.textarea,
            width: '350px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
        ],
      },
      // 运行结果区间设置
      userFormulaPortionTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '区间',
            key: 'portionSet',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '参考值，即落入某区间视同获得此值',
            key: 'refValue',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '备注',
            key: 'portionRemark',
            type: JVXETypes.textarea,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
        ],
      },
      url: {
        add: '/userFormula/userFormula/add',
        edit: '/userFormula/userFormula/edit',
        queryById: '/userFormula/userFormula/queryById',
        userFormulaDetail: {
          list: '/userFormula/userFormula/queryUserFormulaDetailByMainId',
        },
        userFormulaPortion: {
          list: '/userFormula/userFormula/queryUserFormulaPortionByMainId',
        },
      },
      visible: false,
      drawerWidth: '90%',
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {},
  methods: {
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 300) {
        this.drawerWidth = screenWidth
      } else {
        this.drawerWidth = 500
      }
    },
    show(formulaId) {
      this.visible = true
      this.formulaId = formulaId
      this.loadData()
    },
    addLink() {
      this.searchOptions = []
      var that = this
      let params = { id: this.formulaId }
      getAction(this.url.userFormulaDetail.list, params)
        .then((res) => {
          let { result } = res
          if (result) {
            this.insertFunVisible = true
            this.addFunText = ''
            if (Array.isArray(result)) {
              result.forEach((element) => {
                that.searchOptions.push({ text: element.funId, value: element.funId })
              })
            } else if (Array.isArray(result.records)) {
              result.records.forEach((element) => {
                that.searchOptions.push({ text: element.funId, value: element.funId })
              })
            }
          }
        })
        .finally(() => {})
    },
    handleAddFunCancel() {
      this.insertFunVisible = false
    },
    handleAddFunSubmit() {
      var that = this
      this.createForm.validateFields((err, fieldsValue) => {
        if (err) {
          return
        }
        that.$refs.wText.addTag(that.addFunText)
        that.insertFunVisible = false
        var re = /<(?:.)*?>/g // *? 意味着匹配任意数量的重复
        that.model.formulaContent = that.model.formulaContentHtml.replace(re, '@')
      })
    },
    addTagFormulaContent(funText) { 
      this.$refs.wText.addTag(funText)
    },
    refreshFormulaContent(funIdObj) {
      var that = this;
      that.model.formulaContentHtml = that.model.formulaContentHtml.replaceAll(funIdObj['oldFunId'],  funIdObj['newFunId'])
      that.handleSave();
    },
    loadData() {
      this.title = (this.formulaId == 0 ? '新建' : '编辑') + '算法'
      if (this.formulaId && this.formulaId > 0) {
        this.isEdit = true
        let params = { id: this.formulaId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.model = res.result
          }
        })
      } else {
        this.isEdit = false
        this.model.formulaName = ''
        this.model.remark = ''
        this.model.formulaContent = ''
        this.model.formulaContentHtml = ''
      }
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    handleCancel() {
      this.visible = false
      //this.$router.push({ path: '/corp/userFormula/userFormulaList' })
    },
    handleSave() {
      var that = this
      var url = that.url.add
      if (this.formulaId && this.formulaId > 0) {
        url = that.url.edit
        that.model.id = this.formulaId
      } 
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.loading = true 
          var re = /<(?:.)*?>/g // *? 意味着匹配任意数量的重复  
          that.model.formulaContent = that.model.formulaContentHtml.replaceAll('<br>','').replace(re, '@')
          that.model.formulaContent = that.model.formulaContent.replaceAll("&gt;",">").replaceAll("&lt;","<");
          postAction(url, that.model).then((res) => {
            that.loading = false
            if (res.success) { 
              that.$message.success(res.message)
              that.formulaId = res.result.id
              that.isEdit = true
              that.title = '编辑算法'
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          })
        }
      })
    },
    validateUsername(rule, value, callback) {
      var params = {
        tableName: 'user_formula',
        fieldName: 'formula_name',
        fieldVal: value,
        dataId: this.formulaId,
      }
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback()
        } else {
          callback('名称已存在!')
        }
      })
    },
  },
}
</script> 